package com.company;

import java.util.Arrays;

/**
 * 剑指 Offer 05. 替换空格
 * 请实现一个函数，把字符串 s 中的每个空格替换成"%20"
 */

public class Solution05 {
    public static String replaceSpace(String s) {
        StringBuilder sb=new StringBuilder();
        for (int i=0;i<s.length();i++)
        {
            if (s.charAt(i)==' ')
            {
                sb.append("  ");
            }
        }
        if (sb.length()==0)
        {
            return s;
        }
        int left=s.length()-1;
        s+=sb;
        int right=s.length()-1;
        char[] chars=s.toCharArray();
        while(left>=0)
        {
            if (chars[left]==' ')
            {
                chars[right--]='0';
                chars[right--]='2';
                chars[right]='%';
            }else
            {
                chars[right]=chars[left];
            }
            left--;
            right--;
        }
        return new String(chars);
    }

    public static void main(String[] args) {
        String s="We are happy.";
        System.out.println(replaceSpace(s));
    }
}
